package com.wac.data.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class UpLoad {
	private Map<String, Object> result;
	private File fileTempObj;

	//文件夹路径
	private static String IMAGE = "D:/webAssets/image";
	//用户头像路径
	private static String HEAD = IMAGE + "/user_head/";
	//用户背景图路径
	private static String BACKGROUND = IMAGE + "/user_background/";
	//文章封面图路径
	private static String ARTICLE = IMAGE + "/article/";
	//动态图片列表路径
	private static String DYNAMIC = IMAGE + "/dynamic/";

	//服务器域名
	private static String DOMAIN = "http://192.168.31.118:8080";
	// private static String DOMAIN = "http://47.113.227.183:8080";

	//1是头像 2是背景图 3是文章 4是动态
	private String getUrl(MultipartFile file, String fileName, int where) {
		String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
		String filePath = null;
		String returnFileUrl = null;
		//返回的虚拟路径
		switch (where) {
			case 1: {
				filePath = HEAD + fileName + suffixName;
				returnFileUrl = "/image/user_head/" + fileName + suffixName;
				break;
			}
			case 2: {
				filePath = BACKGROUND + fileName + suffixName;
				returnFileUrl = "/image/user_background/" + fileName + suffixName;
				break;
			}
			case 3: {
				filePath = ARTICLE + fileName + suffixName;
				returnFileUrl = "/image/article/" + fileName + suffixName;
				break;
			}
			case 4: {
				filePath = DYNAMIC + fileName + suffixName;
				returnFileUrl = "/image/dynamic/" + fileName + suffixName;
				break;
			}
		}
		fileTempObj = new File(filePath);
		try {
			file.transferTo(fileTempObj);
		} catch (Exception e) {
			this.result.put(fileName, e.getMessage());
			return "上传失败";
		}
		return DOMAIN + returnFileUrl;
	}

	public Map<String, Object> upLoadFiles(List<MultipartFile> multipartFile, int where) {
		this.result = new HashMap<>();
		String url = null;
		for (int i = 0; i < multipartFile.size(); i++) {
			String fileNmae = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
			if (i == 0) {
				url = getUrl(multipartFile.get(i), fileNmae, where);
				continue;
			}
			url = url + "," + getUrl(multipartFile.get(i), fileNmae, where);
		}
		this.result.put("url", url);
		return this.result;
	}

	public boolean deleteFile(String url) {
		System.out.println("需要删除->" + url);
		url = url.replace(DOMAIN, "");
		url = "D:/webAssets" + url;
		File file = new File(url);
		if (!file.exists()) {
			System.out.println("本身不存在");
			return true;
		}
		System.out.println("执行删除");
		file.delete();
		return true;
	}
}
